#include "ibas_in.h"
#include "ibas_api.h"

char		*g_ibp_ibmc_api_kernel_version = IBP_VERSION ;

struct IbasEnv		*g_p_ibas_env = NULL ;
struct FuncStack	*g_funcstack = NULL ;

const char *IBASGetThisNode()
{
	return g_p_ibas_env->p_this_node_unit->node;
}

const char *IBASGetThisApp()
{
	return g_p_ibas_env->p_this_app_unit->app;
}

struct HttpBuffer *IBASGetResponseBody()
{
	return g_p_ibas_env->accepted_session.rsp_body;
}

int IBASSendResponseAhead()
{
	struct IbasEnv		*p_env = g_p_ibas_env ;
	
	struct HttpBuffer	*rsp_buf = NULL ;
	char			*msg = NULL ;
	int			msg_len ;
	
	struct timeval		sending_response ;
	
	int			nret = 0 ;
	
	nret = AfterCallSomain( p_env ) ;
	if( nret )
	{
		ERRORLOGSG( "AfterCallSomain failed[%d]" , nret );
		return nret;
	}
	
	rsp_buf = GetHttpResponseBuffer( p_env->accepted_session.http ) ;
	msg = GetHttpBufferBase( rsp_buf , & msg_len ) ;
	DEBUGHEXLOGSG( msg , msg_len , "ResponseBuffer(decrypt) [%d]bytes" , msg_len );
	
	gettimeofday( & sending_response , NULL );
	
	nret = OnSendResponse( p_env ) ;
	
	gettimeofday( & (p_env->p_worker_detail->processing_info.timeval_stat.finish) , NULL );
	DiffTimeval( & sending_response , & (p_env->p_worker_detail->processing_info.timeval_stat.finish) , & (p_env->p_worker_detail->processing_info.timeval_stat.sending_response_elapse) );
	
	return IBP_IBAS_ERROR_A_S(nret);
}

int IBASGetResponseFlag()
{
	return g_p_ibas_env->accepted_session.response_flag;
}

int IBASGetRequestFileCount( struct IbasAddonFiles *addon_files )
{
	return addon_files->req_filecount;
}

char *IBASGetRequestFile( struct IbasAddonFiles *addon_files , int index )
{
	return addon_files->req_filename[index];
}

int IBASGetRepsonseFileCount( struct IbasAddonFiles *addon_files )
{
	return addon_files->rsp_filecount;
}

int IBASPutResponseFile( struct IbasAddonFiles *addon_files , char *filename )
{
	if( addon_files->rsp_filecount >= sizeof(addon_files->rsp_filename)/sizeof(addon_files->rsp_filename[0]) )
		return IBP_IBAS_ERROR_TOO_MANY_RESPONSE_FILES;
	
	strncpy( addon_files->rsp_filename[addon_files->rsp_filecount++] , filename , MIN(sizeof(addon_files->rsp_filename[0])-1,strlen(filename)) );
	
	return 0;
}

void IBASGetPathFilename( char *filename , char *pathfilename , int sizeof_pathfilename )
{
	char		*file_dir = NULL ;
	
	memset( pathfilename , 0x00 , sizeof_pathfilename );
	file_dir = getenv("IBP_FILEDIR" ) ;
	if( file_dir )
		snprintf( pathfilename , sizeof_pathfilename-1 , "%s/%s" , file_dir , filename );
	else
		snprintf( pathfilename , sizeof_pathfilename-1 , "%s/file/%s" , getenv("HOME") , filename );
	
	return;
}

struct IbasEnv *IBASGetEnv()
{
	return g_p_ibas_env;
}

